import React, { Component } from 'react';
import { View, SectionList, Text, ActivityIndicator, StyleSheet } from 'react-native';
import { queryToday } from '../common/Service';
import GankTodayCell from "../widgets/GankTodayCell";

export default class GankTodayScreen extends Component {

  static navigationOptions = {
    headerTitle: '今日热门'
  };

  constructor(props) {
    super(props);
    this.state = {
      sectionData: [],      // SectionList数据源
      loaded: false,  // 用来控制loading视图的显示，当数据加载完成，loading视图不再显示
    };
  }

  componentDidMount() {
    this.loadToday();
  }

  render() {
    if (!this.state.loaded) {
      return (
        <View style={styles.loadingView}>
          <ActivityIndicator animating={true} size="small" />
          <Text style={{ color: '#666666', paddingLeft: 10 }}>努力加载中</Text>
        </View>
      )
    }
    return (
      <SectionList
        keyExtractor={this._keyExtractor}
        renderSectionHeader={this._renderSectionHeader}
        renderItem={this._renderItem}
        sections={this.state.sectionData}
      />
    )
  }

  _keyExtractor = (item) => item._id;

  _renderSectionHeader = (item) => {
    console.log(item);
    let sectionObj = item.section;
    let title = sectionObj.title;
    return (
      <View style={styles.sectionHeader}>
        <Text style={styles.sectionTitle}>{title}</Text>
      </View>
    )
  };

  _renderItem = (data) => {
    let item = data.item;
    return (
      <GankTodayCell item={item} onPress={() => {
        console.log('点击了Item----' + item.desc);
      }} />
    )
  };

  loadToday() {
    let that = this;
    fetch(queryToday()).then((response) => response.json()).then(
      (json) => {
        console.log(json);
        let sectionList = [];
        Object.keys(json.results).forEach(function (key) {
          console.log('key = ' + key);
          sectionList.push(
            { title: key, data: json.results[key] },
          )
        })
        that.setState({
          sectionData: sectionList,
          loaded: true
        })
      }).catch((e) => {
        console.log("加载失败");
        that.setState({
          loaded: true
        })
      }).done();
  }
}
const styles = StyleSheet.create({
  loadingView: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10
  },
  sectionHeader: {
    padding: 10,
    backgroundColor: '#f3c2a1'
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold'
  }
});